<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-table :selected-row-keys="selectedRowKeys" @select-change="(val) => { selectedRowKeys = val }" rowKey="id"
      :data="data" :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #name="{ row }">
        <t-input style="display: inline-block" clearable
          @change="() => { if (row.name !== '') { row.nameStatus = 'default' } }" :status="row.nameStatus"
          v-model="row.name">
          <div slot="tips" v-if="row.nameStatus === 'error'">不能为空</div>
        </t-input>
      </template>
      <template #op="{ row }">
        <file-upload :status="row.fileStatus" v-model="row.sysAttMainVo.sysAttMainIds"
          :fileList.sync="row.sysAttMainEntities" :multiple="true"
          accept="image/*,.pdf,video/*,audio/*,.doc,.docx,.txt">
          <t-button variant="outline">
            <t-icon name="cloud-upload" slot="icon" />
            点击上传
          </t-button>
        </file-upload>
      </template>
      <template #carrierForm="{ row }">
        <t-select @change="(val, content) => { if (row.carrierForm !== '') { row.carrierFormStatus = 'default' } }"
          style="width: 160px;display: inline-block" v-model="row.carrierForm" clearable placeholder="载体形式"
          :options="dict.type.carrier_form" :status="row.carrierFormStatus">
          <div slot="tips" v-if="row.carrierFormStatus === 'error'">不能为空</div>
        </t-select>
      </template>
      <template #spreadAmount="{ row }">
        <t-input-number v-model="row.spreadAmount" theme="row" :min="0" :disabled="false" suffix="次"
          style="width: 160px;display: inline-block"
          @change="() => { if (row.spreadAmount !== '') { row.spreadAmountStatus = 'default' } }"
          :status="row.spreadAmountStatus">
          <div slot="tips" v-if="row.spreadAmountStatus === 'error'">不能为空</div>
        </t-input-number>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData" :disabled="this.data.length >= 5">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else style="width: 100%;">
    <t-table rowKey="id" :data="data" :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>

      <template #carrierForm="{ row }">
        {{ row.carrierForm | filterByDict(dict.type.carrier_form) }}
      </template>

      <template #op="{ row }">

        <div v-for="(item, index) in row.sysAttMainEntities" :key="index">
          <a class="t-button-link" target="_blank" :href="item.fullFilePath">
            {{ item.fileName }}
          </a>
        </div>

      </template>
    </t-table>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  dicts: ["carrier_form"],
  name: "base-publicity",
  components: {
    FileUpload
  },
  props: {
    objId: [String, Number],
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      nameOptions: [],
      leaderLoading: false,
      dictTypes: {},
      profTitOptions: [],
      selectedRowKeys: [],
      dialogOpen: false,
      visible: true,
      formData: {
        sort: null,
        userName: '',
      },
      rules: {
        // name: [
        //   {
        //     required: true,
        //     message: "不能为空",
        //   },
        // ],
        name: [
          {
            required: true,
            message: "不能为空",
          },
        ],
        carrierForm: [
          {
            required: true,
            message: "不能为空",
          },
        ],
        spreadAmount: [
          {
            required: true,
            message: "不能为空",
          },
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 80
        },
        {
          colKey: 'name',
          title: "宣传品名称",
          align: "center",
          width: 200
        },
        {
          colKey: 'op',
          title: "样品",
          align: "center",
          width: 200
        },
        {
          colKey: 'carrierForm',
          title: "载体形式",
          align: "center",
          width: 200
        },
        {
          colKey: 'spreadAmount',
          title: "传播量",
          align: "center",
          width: 200,
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "宣传品名称",
          align: "center",
          width: 200
        },
        {
          colKey: 'op',
          title: "样品",
          align: "center",
          width: 200
        },
        {
          colKey: 'carrierForm',
          title: "载体形式",
          align: "center",
          width: 200
        },
        {
          colKey: 'spreadAmount',
          title: "传播量",
          align: "center",
          width: 200,
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler (val) {
        const newData = this.data.map((val, index) => ({ ...val, sort: index + 1 }))
        this.$emit("input", newData);
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.length > 0) {
          const newArr = val.map(data => ({
            ...data,
            initType: 'init',
            sysAttMainVo: {
              sysAttMainIds: data?.sysAttMainVo?.sysAttMainIds || []
            },
            sysAttMainEntities: data.sysAttMainEntities?.map(val => ({
              ...val,
              name: val.fileName,
              url: val.fullFilePath,
              fullFilePath: val.fullFilePath,
              id: val.id,
              filePath: val.filePath
            })),
          }))
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
  },

  methods: {
    checkData () {
      const title = "宣传品"
      const isValidate = this.data.every((val, index) => {
        Object.keys(val).forEach(item => {
          if (val[item] === null) {
            val[item] = ""
          }
        })
        if (!val.name) {
          this.$set(this.data[index], 'nameStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"宣传品名称"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'nameStatus', 'default')

        if ((val.sysAttMainVo?.sysAttMainIds && val.sysAttMainVo?.sysAttMainIds?.length <= 0) || !val.sysAttMainVo?.sysAttMainIds) {
          this.$set(this.data[index], 'fileStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"样品"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'fileStatus', 'default')

        if (!val.carrierForm) {
          this.$set(this.data[index], 'carrierFormStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"载体形式"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'carrierFormStatus', 'default')

        if (!val.spreadAmount) {
          this.$set(this.data[index], 'spreadAmountStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"传播量"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'spreadAmountStatus', 'default')
        return true;
      });
      return isValidate;
    },
    addData () {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        baseId: this.objId,
        name: '',
        sysAttMainVo: {
          sysAttMainIds: [],
        },
        carrierForm: "",
        spreadAmount: "",
      })
    },
    upData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped>
::v-deep .t-upload__single-display-text {
  justify-content: center !important;
}
</style>
